<?php

/* 
 * Twilio intregration with Worktive
 * 
 * Author: Yong Qui Zheng
 */
        require '../../slimloader/Slim/Slim.php';
	
	require '../helpers/DbHelper.php';
	require '../helpers/GeneralUtil.php';
	require '../helpers/Config.php';
        require 'twilio-php-master/Services/Twilio.php';
	\Slim\Slim::registerAutoloader();
	$app = new \Slim\Slim(array(
		'debug'=>true
	));
	$app->get('/verification/:number/:apikey', function ($phoneNumber,$apikey) use ($config) { 
		if($apikey!=$config['devapipassword']){
			echo json_encode(generateError('0','Miss Match API Key'));
			exit;
		}
                $respData=array();
		if($phoneNumber!=null && $phoneNumber!=""){
                    $code = genVerificationCode(5);
                    if(preg_match('/^\d{10}$/',$phoneNumber)){
                        
                        // this mean it is a valid 10 digit phone number
                        try{
                            $client = new Services_Twilio($config['twilio']['sid'],$config['twilio']['authToken'] );
                            $verificationMsg='Worktive app Verification code: '.$code;
                            $message = $client->account->messages->sendMessage($config['twilio']['fromNumber'],$phoneNumber,$verificationMsg);
                            $respData= generateError("1","A notification has sent to your phone");
                            $respData['code']="$code";
                            
                        }catch (Services_Twilio_RestException $e){
                            $respData=generateError("0",$e->getMessage());
                        }
                    }else{
                        $respData=  generateError('0', 'Invalid phone number');
                    }
                }else{
                    $respData=generateError("0", "Phone Number require");   
                }
                echo json_encode($respData);
	});
	$app->run();

?>
